package day09.test3;

class Bank {
    private int money;

    public Bank(int money) {
        this.money = money;
    }

    public synchronized void Withdraw_Code_Method(double num) throws InterruptedException {
        while(true){
            if(this.money<num)
            {
                break;
            }
            if (this.money >= num) {
                System.out.println(Thread.currentThread().getName() + "准备取钱");
                Thread.sleep(500);
                this.money -= num;
                System.out.println(Thread.currentThread().getName() + "取钱成功,还剩" + this.money + "钱");
            } else {
                System.out.println("账户里面没有这么多钱");
            }
            try {
                notifyAll();
                if(this.money>0)
                {
                    wait();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void Withdraw_Code_Block(double num) throws InterruptedException {
        synchronized (this) {
            while(true){
                if(this.money<num)
                {
                    break;
                }
                if (this.money >= num) {
                    System.out.println(Thread.currentThread().getName() + "准备取钱");
                    Thread.sleep(500);
                    this.money -= num;
                    System.out.println(Thread.currentThread().getName() + "取钱成功,还剩" + this.money + "钱");
                } else {
                    System.out.println("账户里面没有这么多钱");
                }
                try {
                    notifyAll();
                    if(this.money>0)
                    {
                        wait();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }


        }
    }
}

class Withdraw implements Runnable {

    private Bank bank;
    private double num;

    public Withdraw(Bank bank, double num) {
        this.bank = bank;
        this.num = num;
    }

    @Override
    public void run() {
        try {
            this.bank.Withdraw_Code_Block(this.num);
            //this.bank.Withdraw_Code_Method(this.num);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

public class test {
    public static void main(String[] args) {

        Bank bank = new Bank(10000);

        Thread thread1 = new Thread(new Withdraw(bank, 100), "线程1");
        Thread thread2 = new Thread(new Withdraw(bank, 100), "线程2");

        thread1.start();
        thread2.start();

    }
}